package com.personalblog.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录验证过滤器
 * @author jxau_scf
 * @date 2021/4/20 - 12:20
 */
public class LoginCheckPermissionFilter extends AuthorizationFilter {
    private static final Logger logger = LoggerFactory.getLogger(LoginCheckPermissionFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        String url = req.getRequestURI();
        try {
            Subject subject = SecurityUtils.getSubject();
            return subject.isPermitted(url);
        }catch (Exception e){
            logger.error("Check perssion error", e);
        }
        return false;
    }


    /**
     * 在onAccessDenied方法中，如果用户身份为空，说明未登录，则跳转到登录页面，如果未指定跳转的路径，Shiro给了默认值的跳转页面 /login.jsp
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null){
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse resp = (HttpServletResponse)response;
            resp.sendRedirect(req.getContextPath() + "/admin");
//            saveRequestAndRedirectToLogin(request,response);
        }else {
            return true;
        }
        return false;
    }
}
